﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Pluralization;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration.Types;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.ModelConfiguration.Edm;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Utilities;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;

namespace WinnerCMS.Data
{
    /// <summary>
    /// 自定义前缀表名
    /// </summary>
    /// <remarks>https://msdn.microsoft.com/en-us/data/jj819164.aspx</remarks>
    public class CMSTableConvention : IStoreModelConvention<EntityType>, IConvention
    {
        /// <summary>
        /// 重写
        /// </summary>
        /// <param name="item"></param>
        /// <param name="model"></param>
        public void Apply(EntityType item, DbModel model)
        {
            var entitySet = model.StoreModel.Container.EntitySets.SingleOrDefault(e => e.ElementType == GetRootType(item));
            if (entitySet != null)// && !entitySet.Table.StartsWith("CMS_"))//预防执行两遍的bug
            {
                entitySet.Table = "CMS_"+ entitySet.Table;
            }
        }

        public static EntityType GetRootType(EntityType entityType)
        {
            EdmType rootType = entityType;

            while (rootType.BaseType != null)
            {
                rootType = rootType.BaseType;
            }

            return (EntityType)rootType;
        }
    }
}
